/*
 * XQVariable.java
 */

package xq.api;

import java.io.Serializable;
import static xq.util.CommonUtil.blank;

/**
 *
 * @author ThorntonRP
 */
public final class XQVariable implements Serializable {

	private static final long serialVersionUID = 6247837154990714077L;
	
	public static enum Multiplicity {
		
		EXACTLY_ONE(""),
		ZERO_OR_ONE("?"),
		ZERO_OR_MORE("*"),
		ONE_OR_MORE("+");

		public static Multiplicity getMultiplicity(String value) {
			for (Multiplicity m : values()) {
				if (m.value.equals(value)) {
					return m;
				}
			}
			return null;
		}
		
		private final String value;
		
		private Multiplicity(String value) {
			this.value = value;
		}

		public String getValue() {
			return value;
		}
	}
	
	private final String name;
	private final String type;
	private final Multiplicity multiplicity;

	public XQVariable(String name, String type, Multiplicity multiplicity) {
		if (blank(name)) {
			throw new IllegalArgumentException("Invalid parameter name: " + name);
		} else {
			if (blank(type)) {
				type = "xs:string"; // Assume xs:string by default rather than xs:anyType
			}
			if (multiplicity == null) {
				multiplicity = Multiplicity.EXACTLY_ONE;
			}
		}
		this.name = name;
		this.type = type;
		this.multiplicity = multiplicity;
	}

	public String getName() {
		return name;
	}

	public String getType() {
		return type;
	}
	
	public Multiplicity getMultiplicity() {
		return multiplicity;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		} else if (o instanceof XQVariable) {
			return this.name.equals(((XQVariable) o).name);
		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		int hash = 7;
		hash = 97 * hash + name.hashCode();
		return hash;
	}

	@Override
	public String toString() {
		return "$" + name + " as " + type + multiplicity.getValue();
	}
}
